package com.android.task6;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;

/**
 * Class for handling the contact response operation.
 */
public class BluetoothServer {
	
	Contact contact;
	BluetoothAdapter bluetoothAdapter;
	ContactSharing activity;
	
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static final String NAME = "BluetoothContactSharing";
	
	public BluetoothServer(Contact contact, BluetoothAdapter bluetoothAdapter, ContactSharing activity){
		this.contact = contact;
		this.bluetoothAdapter = bluetoothAdapter;
		this.activity = activity;
		
		new Thread(new serverThread(this.contact, this.bluetoothAdapter)).start();
		
	}
	
	public void setContact(Contact contact){
		this.contact = contact;
	}
	
	private class serverThread implements Runnable{
		
		Contact contact;
		BluetoothAdapter bluetoothAdapter;
		
		public serverThread(Contact contact, BluetoothAdapter bluetoothAdapter){
			this.contact = contact;
			Log.i("bt","contact: "+contact.getFullName());
			this.bluetoothAdapter = bluetoothAdapter;
		}
		@Override
		public void run() {
			
			BluetoothServerSocket serverSocket;
			BluetoothSocket clientSocket;
			ObjectOutputStream outputStream;
			
			try {
				Log.i("bt","setting serverSocket");
				serverSocket = this.bluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
				Log.i("bt","waiting for request");	
				clientSocket = serverSocket.accept();
				Log.i("bt","creating outputStream");
				outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
				Log.i("bt","writing object");
				outputStream.writeObject(this.contact);
				Log.i("bt", "object written");
				
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}

	}
	
}
